package com.company.thread;


/**
 * 超时效果增加
 */

public class GuardedObject2 {


    private Object response;


    public Object getResponse(long timeout) {
        synchronized (this) {
            long begin = System.currentTimeMillis();
            long passedTime = 0;
            while (response == null) {
                long waitTime = timeout-passedTime;
                if (waitTime <= 0) {
                    break;
                }
                try {
                    this.wait(waitTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                passedTime = System.currentTimeMillis()-begin;

            }
        }
        return response;
    }


    public void finishResponse(Object response){
        synchronized (this) {
            this.response = response;
            this.notifyAll();
        }
    }

}
